package com.terracloud.server.service.stats;

import com.terracloud.server.queue.util.TbCoreComponent;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.*;

/**
 * Prometheus指标查询服务
 * 用于从Prometheus查询设备指标数据
 */
@Service
@TbCoreComponent
@Slf4j
public class PrometheusMetricsQueryService {

    @Setter
    @Value("${prometheus.url:http://148.70.47.141:30090}")
    private String prometheusUrl;
    
    @Setter
    @Value("${grafana.alerts.url:http://148.70.47.141:31000/api/alertmanager/grafana/api/v2/alerts}")
    private String grafanaAlertsUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 查询设备的指标数据
     *
     * @param deviceId 设备ID
     * @return 指标数据映射
     */
    public Map<String, Object> queryDeviceMetrics(String deviceId) {
        Map<String, Object> metrics = new HashMap<>();
        log.info("查询设备指标信息-------");

        try {
            // CPU负载率
            Double cpuLoad = queryMetric("device_cpu_load_percentage", deviceId);
            metrics.put("cpuLoadPercentage", cpuLoad);

            // 内存总量
            Double memoryTotal = queryMetric("device_memory_total_bytes", deviceId);
            metrics.put("memoryTotalBytes", memoryTotal);

            // 可用内存量
            Double memoryAvailable = queryMetric("device_memory_available_bytes", deviceId);
            metrics.put("memoryAvailableBytes", memoryAvailable);

            // 内存使用占比
            if (memoryTotal != null && memoryTotal > 0 && memoryAvailable != null) {
                double memoryUsed = memoryTotal - memoryAvailable;
                double memoryUsagePercentage = (memoryUsed / memoryTotal) * 100;
                metrics.put("memoryUsagePercentage", memoryUsagePercentage);
            }

            // 磁盘总量
            Double diskTotal = queryMetric("device_disk_total_bytes", deviceId);
            metrics.put("diskTotalBytes", diskTotal);

            // 磁盘可用空间
            Double diskAvailable = queryMetric("device_disk_available_bytes", deviceId);
            metrics.put("diskAvailableBytes", diskAvailable);

            // 磁盘使用占比
            if (diskTotal != null && diskTotal > 0 && diskAvailable != null) {
                double diskUsed = diskTotal - diskAvailable;
                double diskUsagePercentage = (diskUsed / diskTotal) * 100;
                metrics.put("diskUsagePercentage", diskUsagePercentage);
            }

            // 网络上传速率 (1小时每分钟数据)
            long endTime = System.currentTimeMillis() / 1000; // 当前时间戳(秒)
            long startTime = endTime - 3600; // 1小时前的时间戳(秒)
            long step = 60; // 每分钟一个数据点
            
            List<MetricPoint> networkUpload = queryMetricRange("device_network_bytes_upload", deviceId, startTime, endTime, step);
            metrics.put("networkUploadBytes", networkUpload);

            // 网络下载速率 (1小时每分钟数据)
            List<MetricPoint> networkDownload = queryMetricRange("device_network_bytes_down", deviceId, startTime, endTime, step);
            metrics.put("networkDownloadBytes", networkDownload);

            // vpn状态
            Double vpnStatus = queryMetric("terra_cloud_vpn_connection_status", deviceId);
            metrics.put("vpnStatus", vpnStatus);

            // vpn连接时长
            metrics.put("vpnTime", 0.0);

            // 告警数量
            // 告警列表
            // 从Grafana获取告警信息
            List<Map<String, Object>> grafanaAlerts = queryGrafanaAlertsByDevice(deviceId);
            metrics.put("alertCount", grafanaAlerts.size());
            metrics.put("alertList", grafanaAlerts);
            
            // 查询数据采集相关指标
            Map<String, Object> dataCollectionMetrics = queryDataCollectionMetrics(deviceId);
            metrics.put("dataCollectionMetrics", dataCollectionMetrics);
            
            // 查询数据交付相关指标
            Map<String, Object> dataDeliveryMetrics = queryDataDeliveryMetrics(deviceId);
            metrics.put("dataDeliveryMetrics", dataDeliveryMetrics);
            
            // 查询数据产品相关指标
            Map<String, Object> dataProductMetrics = queryDataProductMetrics(deviceId);
            metrics.put("dataProductMetrics", dataProductMetrics);
            
            // 查询数据资源相关指标
            Map<String, Object> dataSourceMetrics = queryDataSourceMetrics(deviceId);
            metrics.put("dataSourceMetrics", dataSourceMetrics);
            
            // 查询数据任务状态分类统计
            Map<String, Object> dataTaskStatusSummary = queryDataTaskStatusSummary(deviceId);
            metrics.put("dataTaskStatusSummary", dataTaskStatusSummary);

        } catch (Exception e) {
            log.error("查询设备{}的指标数据失败", deviceId, e);
        }

        return metrics;
    }

    /**
     * 查询数据采集相关指标（仅返回运行中和最近完成的任务）
     *
     * @param deviceId 设备ID
     * @return 数据采集指标列表（运行中和最近完成的任务）
     */
    public Map<String, Object> queryDataCollectionMetrics(String deviceId) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> runningTasks = new ArrayList<>();
        Map<String, Object> latestCompletedTask = null;
        long latestCompletionTime = 0;
        
        try {
            // 查询新的统一数据采集指标
            List<PrometheusResult> results = queryMetricWithLabels("data_collection_info", deviceId);
            
            // 为每个数据采集任务构建完整指标信息
            for (PrometheusResult promResult : results) {
                Map<String, String> metric = promResult.getMetric();
                if (metric != null) {
                    Map<String, Object> taskMetrics = new HashMap<>();
                    
                    // 从标签中获取信息
                    taskMetrics.put("name", metric.getOrDefault("name", ""));
                    taskMetrics.put("status", metric.getOrDefault("status", ""));
                    taskMetrics.put("reason", metric.getOrDefault("reason", ""));
                    taskMetrics.put("type", metric.getOrDefault("type", ""));
                    taskMetrics.put("starttime", metric.getOrDefault("starttime", ""));
                    taskMetrics.put("totaltime", metric.getOrDefault("totaltime", ""));
                    taskMetrics.put("sucesstimes", metric.getOrDefault("sucesstimes", ""));
                    taskMetrics.put("falsetimes", metric.getOrDefault("falsetimes", ""));
                    
                    // 获取持续时间
                    Double duration = getMetricValue(promResult);
                    taskMetrics.put("durationSeconds", duration);
                    
                    String status = (String) taskMetrics.get("status");
                    String startTimeStr = (String) taskMetrics.get("starttime");
                    
                    // 收集运行中的任务
                    if ("ACTIVE".equals(status)) {
                        runningTasks.add(taskMetrics);
                    }
                    // 查找最近完成的任务
                    else if ("COMPLETED".equals(status) && !startTimeStr.isEmpty()) {
                        try {
                            long startTime = Long.parseLong(startTimeStr);
                            if (startTime > latestCompletionTime) {
                                latestCompletionTime = startTime;
                                latestCompletedTask = taskMetrics;
                            }
                        } catch (NumberFormatException e) {
                            log.warn("无法解析开始时间: {}", startTimeStr);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询设备{}的数据采集指标失败", deviceId, e);
        }
        
        result.put("runningTasks", runningTasks);
        result.put("latestCompletedTask", latestCompletedTask);
        return result;
    }
    
    /**
     * 查询数据交付相关指标（仅返回运行中和最近完成的任务）
     *
     * @param deviceId 设备ID
     * @return 数据交付指标列表（运行中和最近完成的任务）
     */
    public Map<String, Object> queryDataDeliveryMetrics(String deviceId) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> runningTasks = new ArrayList<>();
        Map<String, Object> latestCompletedTask = null;
        long latestCompletionTime = 0;
        
        try {
            // 查询新的统一数据交付指标
            List<PrometheusResult> results = queryMetricWithLabels("data_delivery_info", deviceId);
            
            // 为每个数据交付任务构建完整指标信息
            for (PrometheusResult promResult : results) {
                Map<String, String> metric = promResult.getMetric();
                if (metric != null) {
                    Map<String, Object> taskMetrics = new HashMap<>();
                    
                    // 从标签中获取信息
                    taskMetrics.put("name", metric.getOrDefault("name", ""));
                    taskMetrics.put("result", metric.getOrDefault("result", ""));
                    taskMetrics.put("reason", metric.getOrDefault("reason", ""));
                    taskMetrics.put("productid", metric.getOrDefault("productid", ""));
                    taskMetrics.put("productname", metric.getOrDefault("productname", ""));
                    taskMetrics.put("status", metric.getOrDefault("status", ""));
                    taskMetrics.put("starttime", metric.getOrDefault("starttime", ""));
                    taskMetrics.put("totaltime", metric.getOrDefault("totaltime", ""));
                    taskMetrics.put("falsetimes", metric.getOrDefault("falsetimes", ""));
                    
                    // 获取持续时间
                    Double duration = getMetricValue(promResult);
                    taskMetrics.put("durationSeconds", duration);
                    
                    String status = (String) taskMetrics.get("status");
                    String startTimeStr = (String) taskMetrics.get("starttime");
                    
                    // 收集运行中的任务
                    if ("ACTIVE".equals(status)) {
                        runningTasks.add(taskMetrics);
                    }
                    // 查找最近完成的任务
                    else if (("TASK_COMPLETED".equals(status) || "COMPLETED".equals(status)) && !startTimeStr.isEmpty()) {
                        try {
                            long startTime = Long.parseLong(startTimeStr);
                            if (startTime > latestCompletionTime) {
                                latestCompletionTime = startTime;
                                latestCompletedTask = taskMetrics;
                            }
                        } catch (NumberFormatException e) {
                            log.warn("无法解析开始时间: {}", startTimeStr);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询设备{}的数据交付指标失败", deviceId, e);
        }
        
        result.put("runningTasks", runningTasks);
        result.put("latestCompletedTask", latestCompletedTask);
        return result;
    }
    
    /**
     * 查询数据产品相关指标
     *
     * @param deviceId 设备ID
     * @return 数据产品指标映射
     */
    public Map<String, Object> queryDataProductMetrics(String deviceId) {
        Map<String, Object> metrics = new HashMap<>();
        try {
            // 数据产品总量
            Double total = queryMetric("data_production_total", deviceId);
            metrics.put("total", total != null ? total.intValue() : 0);
            
            // 数据产品已用
            Double used = queryMetric("data_production_used", deviceId);
            metrics.put("used", used != null ? used.intValue() : 0);
            
            // 数据产品未用
            Double unused = queryMetric("data_production_unused", deviceId);
            metrics.put("unused", unused != null ? unused.intValue() : 0);
        } catch (Exception e) {
            log.error("查询设备{}的数据产品指标失败", deviceId, e);
        }
        return metrics;
    }
    
    /**
     * 查询数据资源相关指标
     *
     * @param deviceId 设备ID
     * @return 数据资源指标映射
     */
    public Map<String, Object> queryDataSourceMetrics(String deviceId) {
        Map<String, Object> metrics = new HashMap<>();
        try {
            // 数据资源总量
            Double total = queryMetric("data_source_total", deviceId);
            metrics.put("total", total != null ? total.intValue() : 0);
            
            // 数据资源数据库
            Double database = queryMetric("data_source_database", deviceId);
            metrics.put("database", database != null ? database.intValue() : 0);
            
            // 数据资源API
            Double api = queryMetric("data_source_api", deviceId);
            metrics.put("api", api != null ? api.intValue() : 0);
            
            // 数据资源TXT
            Double txt = queryMetric("data_source_txt", deviceId);
            metrics.put("txt", txt != null ? txt.intValue() : 0);
        } catch (Exception e) {
            log.error("查询设备{}的数据资源指标失败", deviceId, e);
        }
        return metrics;
    }
    
    /**
     * 查询带有标签的指标
     *
     * @param metricName 指标名称
     * @param deviceId   设备ID
     * @return 查询结果列表
     */
    private List<PrometheusResult> queryMetricWithLabels(String metricName, String deviceId) {
        List<PrometheusResult> results = new ArrayList<>();
        try {
            String queryExpression = String.format("%s{instance=\"%s\"}", metricName, deviceId);

            URI uri = UriComponentsBuilder.fromHttpUrl(prometheusUrl)
                    .path("/api/v1/query")
                    .queryParam("query", queryExpression)
                    .build()
                    .encode()
                    .toUri();

            log.debug("查询Prometheus指标: metricName={}, deviceId={}, queryExpression={}",
                    metricName, deviceId, queryExpression);

            ResponseEntity<PrometheusResponse> response = restTemplate.getForEntity(uri, PrometheusResponse.class);

            if (response.getBody() != null && "success".equals(response.getBody().getStatus())) {
                PrometheusData data = response.getBody().getData();
                if (data != null && data.getResult() != null) {
                    results.addAll(data.getResult());
                }
            }
        } catch (Exception e) {
            log.warn("查询指标 {} 失败: {}", metricName, e.getMessage());
        }
        return results;
    }
    
    /**
     * 查询特定标签值的指标
     *
     * @param metricName 指标名称
     * @param deviceId   设备ID
     * @param labelName  标签名称
     * @param labelValue 标签值
     * @return 指标值
     */
    private Double querySpecificMetric(String metricName, String deviceId, String labelName, String labelValue) {
        try {
            String queryExpression = String.format("%s{instance=\"%s\",%s=\"%s\"}", metricName, deviceId, labelName, labelValue);

            URI uri = UriComponentsBuilder.fromHttpUrl(prometheusUrl)
                    .path("/api/v1/query")
                    .queryParam("query", queryExpression)
                    .build()
                    .encode()
                    .toUri();

            ResponseEntity<PrometheusResponse> response = restTemplate.getForEntity(uri, PrometheusResponse.class);

            if (response.getBody() != null && "success".equals(response.getBody().getStatus())) {
                PrometheusData data = response.getBody().getData();
                if (data != null && data.getResult() != null && !data.getResult().isEmpty()) {
                    PrometheusResult result = data.getResult().getFirst();
                    return getMetricValue(result);
                }
            }
        } catch (Exception e) {
            log.warn("查询指标 {} 失败: {}", metricName, e.getMessage());
        }
        return null;
    }
    
    /**
     * 从Prometheus结果中提取指标值
     *
     * @param result Prometheus结果
     * @return 指标值
     */
    private Double getMetricValue(PrometheusResult result) {
        if (result != null && result.getValue() != null && result.getValue().length > 1) {
            try {
                return Double.parseDouble(result.getValue()[1]);
            } catch (NumberFormatException e) {
                log.warn("无法解析指标值: {}", result.getValue()[1]);
            }
        }
        return null;
    }

    /**
     * 查询指定指标的值
     *
     * @param metricName 指标名称
     * @param deviceId   设备ID
     * @return 指标值
     */
    private Double queryMetric(String metricName, String deviceId) {
        try {
            // 简化查询表达式构造，避免复杂的转义
            // 直接使用字符串格式化，确保语法正确
            String queryExpression = String.format("%s{instance=\"%s\"}", metricName, deviceId);

            // 使用 UriComponentsBuilder 确保URL构建正确
            URI uri = UriComponentsBuilder.fromHttpUrl(prometheusUrl)
                    .path("/api/v1/query")
                    .queryParam("query", queryExpression)
                    .build()
                    .encode()
                    .toUri();

            log.debug("查询Prometheus指标: metricName={}, deviceId={}, queryExpression={}",
                    metricName, deviceId, queryExpression);
            log.debug("完整查询URL: {}", uri);

            ResponseEntity<PrometheusResponse> response = restTemplate.getForEntity(uri, PrometheusResponse.class);

            if (response.getBody() != null && "success".equals(response.getBody().getStatus())) {
                PrometheusData data = response.getBody().getData();
                if (data != null && data.getResult() != null && !data.getResult().isEmpty()) {
                    PrometheusResult result = data.getResult().getFirst();
                    if (result.getValue() != null && result.getValue().length > 1) {
                        String value = result.getValue()[1];
                        log.debug("查询到指标 {} 的值: {}", metricName, value);
                        try {
                            // 处理科学计数法格式的数值
                            // 根据数值大小决定是否使用科学计数法
                            return Double.parseDouble(value);
                        } catch (NumberFormatException e) {
                            log.warn("无法解析指标值 '{}' 为数字", value);
                            return null;
                        }
                    }
                } else {
                    log.debug("指标 {} 对于设备 {} 没有数据", metricName, deviceId);
                }
            } else if (response.getBody() != null) {
                log.warn("Prometheus查询返回错误: status={}, errorType={}, error={}",
                        response.getBody().getStatus(),
                        response.getBody().getErrorType(),
                        response.getBody().getError());
            }
        } catch (Exception e) {
            log.warn("查询指标 {} 失败: {}", metricName, e.getMessage());
            // 对于调试，可以打印堆栈跟踪
            if (log.isDebugEnabled()) {
                log.debug("详细错误信息:", e);
            }
        }
        return null;
    }

    /**
     * 查询指定指标在一段时间范围内的值
     *
     * @param metricName 指标名称
     * @param deviceId   设备ID
     * @param start      开始时间戳 (秒)
     * @param end        结束时间戳 (秒)
     * @param step       步长 (秒)
     * @return 指标值列表
     */
    private List<MetricPoint> queryMetricRange(String metricName, String deviceId, long start, long end, long step) {
        List<MetricPoint> metrics = new ArrayList<>();
        try {
            String queryExpression = String.format("%s{instance=\"%s\"}", metricName, deviceId);

            URI uri = UriComponentsBuilder.fromHttpUrl(prometheusUrl)
                    .path("/api/v1/query_range")
                    .queryParam("query", queryExpression)
                    .queryParam("start", start)
                    .queryParam("end", end)
                    .queryParam("step", step)
                    .build()
                    .encode()
                    .toUri();

            log.debug("查询Prometheus指标范围: metricName={}, deviceId={}, queryExpression={}",
                    metricName, deviceId, queryExpression);

            ResponseEntity<PrometheusResponse> response = restTemplate.getForEntity(uri, PrometheusResponse.class);

            if (response.getBody() != null && "success".equals(response.getBody().getStatus())) {
                PrometheusData data = response.getBody().getData();
                if (data != null && data.getResult() != null && !data.getResult().isEmpty()) {
                    PrometheusResult result = data.getResult().getFirst();
                    if (result.getValues() != null) {
                        for (String[] value : result.getValues()) {
                            if (value.length > 1) {
                                try {
                                    long timestamp = Long.parseLong(value[0]);
                                    double metricValue = Double.parseDouble(value[1]);
                                    metrics.add(new MetricPoint(timestamp, metricValue));
                                } catch (NumberFormatException e) {
                                    log.warn("无法解析指标值: timestamp={}, value={}", value[0], value[1]);
                                }
                            }
                        }
                    }
                } else {
                    log.debug("指标 {} 对于设备 {} 在时间范围内没有数据", metricName, deviceId);
                }
            } else if (response.getBody() != null) {
                log.warn("Prometheus范围查询返回错误: status={}, errorType={}, error={}",
                        response.getBody().getStatus(),
                        response.getBody().getErrorType(),
                        response.getBody().getError());
            }
        } catch (Exception e) {
            log.warn("查询指标范围 {} 失败: {}", metricName, e.getMessage());
            if (log.isDebugEnabled()) {
                log.debug("详细错误信息:", e);
            }
        }
        return metrics;
    }

    /**
     * 查询Grafana告警信息
     *
     * @param filters 过滤条件列表，如 ["instance=gw_001", "alert name=HighCPU"]
     * @return 告警信息列表
     */
    public List<Map<String, Object>> queryGrafanaAlerts(String... filters) {
        List<Map<String, Object>> alerts = new ArrayList<>();
        try {
            // 构建查询URL
            UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(grafanaAlertsUrl);
            
            // 添加过滤参数
            for (String filter : filters) {
                uriBuilder.queryParam("filter", filter);
            }

            URI uri = uriBuilder.build().encode().toUri();
            log.debug("查询Grafana告警信息: url={}", uri);

            // 执行查询
            ResponseEntity<Object[]> response = restTemplate.getForEntity(uri, Object[].class);
            
            if (response.getBody() != null) {
                // 将响应转换为Map列表，只保留指定字段
                for (Object alertObj : response.getBody()) {
                    // 安全地进行类型转换
                    if (alertObj instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> originalAlert = (Map<String, Object>) alertObj;
                        Map<String, Object> filteredAlert = new HashMap<>();
                        
                        // 只保留指定的字段
                        if (originalAlert.containsKey("labels")) {
                            filteredAlert.put("labels", originalAlert.get("labels"));
                        }

                        alerts.add(filteredAlert);
                    }
                }
                log.debug("查询到 {} 条Grafana告警信息", alerts.size());
            }
        } catch (Exception e) {
            log.error("查询Grafana告警信息失败: {}", e.getMessage(), e);
        }
        return alerts;
    }
    
    /**
     * 查询指定设备的Grafana告警信息
     *
     * @param deviceId 设备ID
     * @return 告警信息列表
     */
    public List<Map<String, Object>> queryGrafanaAlertsByDevice(String deviceId) {
        return queryGrafanaAlerts("instance=" + deviceId);
    }
    
    /**
     * 根据数据采集和数据交付列表里的status字段进行分类计数返回
     *
     * @param deviceId 设备ID
     * @return 状态分类统计结果
     */
    public Map<String, Object> queryDataTaskStatusSummary(String deviceId) {
        Map<String, Object> summary = new HashMap<>();
        
        try {
            // 直接查询所有数据采集任务并统计状态
            List<PrometheusResult> collectionResults = queryMetricWithLabels("data_collection_info", deviceId);
            List<Map<String, Object>> collectionMetricsList = getMaps(collectionResults);

            // 直接查询所有数据交付任务并统计状态
            List<PrometheusResult> deliveryResults = queryMetricWithLabels("data_delivery_info", deviceId);
            List<Map<String, Object>> deliveryMetricsList = new ArrayList<>();
            
            // 构建数据交付任务列表
            for (PrometheusResult result : deliveryResults) {
                Map<String, String> metric = result.getMetric();
                if (metric != null) {
                    Map<String, Object> taskMetrics = new HashMap<>();
                    taskMetrics.put("status", metric.getOrDefault("status", ""));
                    deliveryMetricsList.add(taskMetrics);
                }
            }
            
            // 分类统计计数
            Map<String, Integer> collectionStatusSummary = categorizeStatusCount(collectionMetricsList);
            Map<String, Integer> deliveryStatusSummary = categorizeStatusCount(deliveryMetricsList);
            
            summary.put("dataCollectionStatusSummary", collectionStatusSummary);
            summary.put("dataDeliveryStatusSummary", deliveryStatusSummary);
        } catch (Exception e) {
            log.error("查询设备{}的数据任务状态统计失败", deviceId, e);
        }
        
        return summary;
    }

    @NotNull
    private static List<Map<String, Object>> getMaps(List<PrometheusResult> collectionResults) {
        List<Map<String, Object>> collectionMetricsList = new ArrayList<>();

        // 构建数据采集任务列表
        for (PrometheusResult result : collectionResults) {
            Map<String, String> metric = result.getMetric();
            if (metric != null) {
                Map<String, Object> taskMetrics = new HashMap<>();
                taskMetrics.put("status", metric.getOrDefault("status", ""));
                collectionMetricsList.add(taskMetrics);
            }
        }
        return collectionMetricsList;
    }

    /**
     * 对指标列表按状态进行分类统计
     *
     * @param metricsList 指标列表
     * @return 分类统计结果
     */
    private Map<String, Integer> categorizeStatusCount(List<Map<String, Object>> metricsList) {
        Map<String, Integer> statusCount = new HashMap<>();
        statusCount.put("inactive", 0);   // INACTIVE
        statusCount.put("completed", 0);   // COMPLETED
        statusCount.put("active", 0);   // ACTIVE
        statusCount.put("paused", 0);   // PAUSED, INCOMPLETED, DB REMOTE ERROR, DB LOCAL ERROR
        
        for (Map<String, Object> metric : metricsList) {
            String status = (String) metric.get("status");
            if (status != null) {
                switch (status) {
                    case "INACTIVE":
                        statusCount.put("inactive", statusCount.get("inactive") + 1);
                        break;
                    case "ACTIVE":
                        statusCount.put("active", statusCount.get("active") + 1);
                        break;
                    case "COMPLETED":
                        statusCount.put("completed", statusCount.get("completed") + 1);
                        break;
                    case "PAUSED":
                    case "INCOMPLETED":
                    case "DB REMOTE ERROR":
                    case "DB LOCAL ERROR":
                        statusCount.put("paused", statusCount.get("paused") + 1);
                        break;
                    default:
                        // 对于未识别的状态，默认归类为"已终止"
                        statusCount.put("paused", statusCount.get("paused") + 1);
                        break;
                }
            }
        }
        
        return statusCount;
    }

    // 原有的内部类保持不变
    @Setter
    @Getter
    public static class PrometheusResponse {
        private String status;
        private String errorType;
        private String error;
        private PrometheusData data;

    }

    @Setter
    @Getter
    public static class PrometheusData {
        private String resultType;
        private java.util.List<PrometheusResult> result;

    }

    @Setter
    @Getter
    public static class PrometheusResult {
        private java.util.Map<String, String> metric;
        private String[] value;
        private String[][] values;

    }

    /**
     * 指标数据点
     */
    @Setter
    @Getter
    public static class MetricPoint {
        private String date;
        private double value;

        public MetricPoint(long timestamp, double value) {
            this.date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(timestamp * 1000));
            this.value = value;
        }
    }
}